<template>
	<cu-custom  bgColor="bg-gray"  :isBack="isBack">
	<!-- Vue 3 正确写法 -->
	<!--    <template #backText>返回</template> -->
		<template #content>Session Details</template>
	</cu-custom>
	
	<view class="content">
		<view class="warning-view-content" v-if="session.stopReason == 'PowerLoss'">
			<image style="width: 44rpx; height: 44rpx;" src="/static/power_loss.png"></image>
			<view style="margin-left: 16rpx;">Power loss at time {{session.chargeEndTime}}</view>
		</view>
		
		<view class="container-view">
			<view class="line-content">
				<view class="line-left">
					<image class="icon-image" src="/static/station_name.png"></image>
					<view style="margin-left: 8rpx;">Station name</view>
				</view>
				<view class="line-right">{{stationName}}</view>
			</view>
			
			<view class="line-content" style="align-items: flex-start;">
				<view class="line-left">
					<image class="icon-image" src="/static/session_location.png"></image>
					<view style="margin-left: 8rpx;">Station address</view>
				</view>
				<view class="line-right" style="width: 55%;">{{stationLocation.houseNumber}}, {{stationLocation.street}}, {{stationLocation.cityName}}, {{stationLocation.countryName}}</view>
			</view>
			
			<view class="line-content">
				<view class="line-left">
					<image class="icon-image" src="/static/session_charge_id.png"></image>
					<view style="margin-left: 8rpx;">Charge point ID</view>
				</view>
				<view class="line-right">{{session.chargeBoxId}}</view>
			</view>
			
			<view class="line-content">
				<view class="line-left">
					<image class="icon-image" src="/static/session_connector.png"></image>
					<view style="margin-left: 8rpx;">Connector</view>
				</view>
				<view class="line-right">{{session.connectorId}}</view>
			</view>
			
			<view class="line-content">
				<view class="line-left">
					<image class="icon-image" src="/static/session_max_power.png"></image>
					<view style="margin-left: 8rpx;">Max. power</view>
				</view>
				<view class="line-right">{{connectorMaxPower}} kW {{connectorType}}</view>
			</view>
			
			<view class="line-content">
				<view class="line-left">
					<image class="icon-image" src="/static/session_transaction_id.png"></image>
					<view style="margin-left: 8rpx;">Transaction ID</view>
				</view>
				<view class="line-right">{{session.transactionId}}</view>
			</view>
			
			<view class="line-content">
				<view class="line-left">
					<image class="icon-image" src="/static/session_start_type.png"></image>
					<view style="margin-left: 8rpx;">Startup method</view>
				</view>
				<view class="line-right">{{session.startupActor}}</view>
			</view>
			
			<view class="line-content">
				<view class="line-left">
					<image class="icon-image" src="/static/session_start_time.png"></image>
					<view style="margin-left: 8rpx;">Charging start time</view>
				</view>
				<view class="line-right">{{session.chargeStartTime}}</view>
			</view>
			
			<view class="line-content">
				<view class="line-left">
					<image class="icon-image" src="/static/session_total_time.png"></image>
					<view style="margin-left: 8rpx;">Total charging time</view>
				</view>
				<view class="line-right">{{session.duration}}</view>
			</view>
			
			<view class="line-content">
				<view class="line-left">
					<image class="icon-image" src="/static/session_total_electric.png"></image>
					<view style="margin-left: 8rpx;">Total energy consumption</view>
				</view>
				<view class="line-right">{{session.energy}} kWh</view>
			</view>
			
			<view class="line-content">
				<view class="line-left">
					<image class="icon-image" src="/static/session_total_price.png"></image>
					<view style="margin-left: 8rpx;">Total price</view>
				</view>
				<view class="line-right" style="color: #466EFF;">{{session.cost}} {{session.currency}}</view>
			</view>
			
			<view class="line-content" style="align-items: flex-start;">
				<view class="line-left">
					<image class="icon-image" src="/static/session_stop_reason.png"></image>
					<view style="margin-left: 8rpx;">Reason for stopping</view>
				</view>
				<view class="line-right" style="width: 45%;">{{session.stopReason}}</view>
			</view>
			
			
		</view>
		<view class="info-content">Billing information</view>
		<view style="padding: 0 32rpx;">
			<view class="idle-free-content">
				<image src="/static/icon_free.png" style="width: 44rpx;height: 44rpx;"></image>
				<view class="idle-free-text">Free idle duration: {{session.idleGraceMinutes}} minutes</view>
			</view>
		</view>
		<view class="bill-content">
			<view v-for="item in details" :key="index"  class="bill-container">
<!-- 				<view style="font-family: PingFang SC; font-size: 28rpx; font-weight: 500; line-height: 48rpx;color: #8E8E90;">2025-09-23</view> -->
				<view class="bill-detail-content" v-if="Number(item.idleDuration) > 0 && Number(item.energy) > 0">
					<view class="time-content">
						<view>{{item.segmentStartTime}}-{{item.segmentEndTime}}</view>
					</view>
					
					<!-- Energy unit price -->
					<view class="line-content">
						<view class="line-left">
							<image class="icon-image" src="/static/session_unit_price.png"></image>
							<view style="margin-left: 8rpx;">Energy unit price</view>
						</view>
						<view class="line-right">{{item.energyPrice}} {{session.currency}}/kWh</view>
					</view>
					
					
					<!-- Energy consumption -->
					<view class="line-content">
						<view class="line-left">
							<image class="icon-image" src="/static/session_capacity.png"></image>
							<view style="margin-left: 8rpx;">Energy consumption</view>
						</view>
						<view class="line-right">{{item.energy}} kWh</view>
					</view>
					
					<!-- Energy cost -->
					<view class="line-content">
						<view class="line-left">
							<image class="icon-image" src="/static/session_cost.png"></image>
							<view style="margin-left: 8rpx;">Energy cost</view>
						</view>
						<view class="line-right" style="color: #466EFF;">{{item.energyCost}} {{session.currency}}</view>
					</view>	
									
					<!-- Idle price -->
					<view class="line-content">
						<view class="line-left">
							<image class="icon-image" src="/static/session_unit_price.png"></image>
							<view style="margin-left: 8rpx;">Idle unit price</view>
						</view>
						<view class="line-right">{{item.idlePrice}} {{session.currency}}/h</view>
					</view>
					
					<!-- Idle duration -->
					<view class="line-content">
						<view class="line-left">
							<image class="icon-image" src="/static/session_unit_price.png"></image>
							<view style="margin-left: 8rpx;">Idle duration</view>
						</view>
						<view class="line-right">{{item.idleStartTime}}-{{item.idleStopTime}}</view>
					</view>
					
					<!-- ldle fee -->
					<view class="line-content">
						<view class="line-left">
							<image class="icon-image" src="/static/session_free.png"></image>
							<view style="margin-left: 8rpx;">ldle fee</view>
						</view>
						<view class="line-right" style="color: #466EFF;">{{item.idleCost}} {{session.currency}}</view>
					</view>				
									
									
				</view>
				
				
				<view class="bill-detail-content" v-else-if="Number(item.idleDuration) > 0">
					<view class="time-content">
						<view>{{item.idleStartTime}}-{{item.idleStopTime}}</view>
					</view>
					
					<!-- Idle price -->
					<view class="line-content">
						<view class="line-left">
							<image class="icon-image" src="/static/session_unit_price.png"></image>
							<view style="margin-left: 8rpx;">Idle unit price</view>
						</view>
						<view class="line-right">{{item.idlePrice}} {{session.currency}}/h</view>
					</view>
					
					<!-- ldle fee -->
					<view class="line-content">
						<view class="line-left">
							<image class="icon-image" src="/static/session_free.png"></image>
							<view style="margin-left: 8rpx;">ldle fee</view>
						</view>
						<view class="line-right" style="color: #466EFF;">{{item.idleCost}} {{session.currency}}</view>
					</view>		
				</view>
				
				<view class="bill-detail-content" v-else>
					<view class="time-content">
						<view>{{item.segmentStartTime}}-{{item.segmentEndTime}}</view>
					</view>
					
					<!-- Energy unit price -->
					<view class="line-content">
						<view class="line-left">
							<image class="icon-image" src="/static/session_unit_price.png"></image>
							<view style="margin-left: 8rpx;">Energy unit price</view>
						</view>
						<view class="line-right">{{item.energyPrice}} {{session.currency}}/kWh</view>
					</view>
					
					<!-- Energy consumption -->
					<view class="line-content">
						<view class="line-left">
							<image class="icon-image" src="/static/session_capacity.png"></image>
							<view style="margin-left: 8rpx;">Energy consumption</view>
						</view>
						<view class="line-right">{{item.energy}} kWh</view>
					</view>
					
					<!-- Energy cost -->
					<view class="line-content">
						<view class="line-left">
							<image class="icon-image" src="/static/session_cost.png"></image>
							<view style="margin-left: 8rpx;">Energy cost</view>
						</view>
						<view class="line-right" style="color: #466EFF;">{{item.energyCost}} {{session.currency}}</view>
					</view>	
				</view>
				

			</view>
			
		</view>
		
		<view style="height: 100rpx;"></view>
		
	</view>
</template>

<script>
	// 则导入时需要使用命名导入
	import   http  from '@/invoice/utils/request.js';
	import cuCustom from '@/colorui/components/cu-custom.vue';
	export default {
		components: {
		    cuCustom
		},
		data() {
			return {
				isBack: false,
				stationName: "",
				connectorType: "",
				stationLocation: {},
				connectorMaxPower: 0,
				session: {},
				details: []
			}
		},
		onLoad(options) {
			
			
			console.log('初始URL参数：', options);
			// console.log("transactionId = "+ options.transactionId)
			if(options.transactionId != null) {
				let transactionId = options.transactionId
				let that = this;
				that.getSessionDetail(transactionId)
			}
		},
		onShow() {
		    // 如果页面被复用，可通过 getCurrentPages() 获取当前页面参数
		    const pages = getCurrentPages();
			console.log(pages)
			if(pages.length == 1){
				this.isBack = false
			}else {
				this.isBack = true
			}
		},
		
		methods: {
			goBack() {
			    uni.navigateBack();
			},
			
			getSessionDetail(transactionId){
				let that = this;
				http.post('charge/session/info', {
				  "transactionId": transactionId
				}, { showLoading: true }) // 显式指定显示加载中
				  .then(data => {
				    console.log('request success:', data);
					var data = data.data
				    that.stationName = data.stationName;
					that.stationLocation = data.stationLocation;
					that.connectorMaxPower = data.connectorMaxPower == null?0:data.connectorMaxPower
					that.connectorType = that.CoverTypeToACDC(data.connectorType)
					var session = data.session
					console.log(session)
					session.energy = that.convertAndDivide(session.energy==undefined?'0':session.energy,4);
					session.cost = that.AddAndRound(session.energyCost,session.idleCost)
	
					session.duration = that.TimeDifferenceToHHmm(session.chargeStartTime,session.chargeEndTime)
					
					session.currency = that.convertCurrencyCodeToSymbol(session.currency)
					session.chargeStartTime = that.formatUTCDateToLocal(session.chargeStartTime,'MM/DD HH:mm') 
					session.chargeEndTime = that.formatUTCDateToLocal(session.chargeEndTime,'MM/DD HH:mm') 
					// session.stopTime = that.formatUTCDateToLocal(session.stopTime,'MM/DD HH:mm') 
					that.session = session;
					
					
					data.details.forEach(function(detail) {
						detail.segmentStartTime = that.formatUTCDateToLocal(detail.segmentStartTime,'HH:mm') 
						detail.segmentEndTime = that.formatUTCDateToLocal(detail.segmentEndTime,'HH:mm') 
						detail.idleStartTime = that.formatUTCDateToLocal(detail.idleStartTime,'HH:mm:ss')
						detail.idleStopTime = that.formatUTCDateToLocal(detail.idleStopTime,'HH:mm:ss') 
						detail.idleCost = that.formatNumber(detail.idleCost,3)
						detail.energyCost = that.formatNumber(detail.energyCost,3)
						detail.energy = that.convertAndDivide(detail.energy==undefined?'0':detail.energy,4);
						// detail.idleDuration = that.SecondsStringToHHmmss(detail.idleDuration)
						that.details.push(detail)
					}, this);
					
					// that.details = data.details;
				  })
				  .catch(error => {
				    console.error('request fail:', error);
				  });
			},
			
			formatUTCDateToLocal(utcTimeString, format = 'YYYY-MM-DD HH:mm:ss') {
				if (utcTimeString == null) {
					return ""
				}
				
				const date = new Date(utcTimeString);
				
				// 检查日期是否有效
				if (isNaN(date.getTime())) {
					throw new Error('无效的时间格式');
				}
				
				// 提取时间组件，包括毫秒
				const options = {
					YYYY: date.getFullYear(),
					MM: String(date.getMonth() + 1).padStart(2, '0'),
					DD: String(date.getDate()).padStart(2, '0'),
					HH: String(date.getHours()).padStart(2, '0'),
					mm: String(date.getMinutes()).padStart(2, '0'),
					ss: String(date.getSeconds()).padStart(2, '0'),
					SSS: String(date.getMilliseconds()).padStart(3, '0'), // 毫秒（3位，带前导零）
					M: date.getMonth() + 1,       // 不带前导零的月份
					D: date.getDate(),            // 不带前导零的日期
					H: date.getHours(),           // 不带前导零的小时
					m: date.getMinutes(),         // 不带前导零的分钟
					s: date.getSeconds(),         // 不带前导零的秒钟
					S: date.getMilliseconds()     // 不带前导零的毫秒
				};
				// 替换格式字符串中的占位符
				return format.replace(/YYYY|MM|DD|HH|mm|ss|SSS|M|D|H|m|s|S/g, match => options[match]);
			},
			
			// 计算两个时间字符串的分钟差
			getTimeDifferenceInMinutes(time1, time2) {
			    // 将时间字符串转换为时间戳（毫秒）
			    const timestamp1 = new Date(time1).getTime();
			    const timestamp2 = new Date(time2).getTime();
			    
			    // 检查时间格式是否有效
			    if (isNaN(timestamp1) || isNaN(timestamp2)) {
			        throw new Error('无效的时间格式');
			    }
			    
			    // 计算毫秒差，转换为分钟并取绝对值
			    const minuteDiff = Math.abs(timestamp1 - timestamp2) / (1000 * 60);
			    
			    // 返回结果可以根据需要取整或保留小数
			    return Math.round(minuteDiff); // 四舍五入取整
			    // 如需保留两位小数可使用：return Number(minuteDiff.toFixed(2));
			},
			
			
			//计算两个 ISO 格式时间字符串的差值并转换为00:00格式
			GetTimeDifference(time1, time2) {
			    // Date对象原生支持解析带毫秒的ISO格式
			    const date1 = new Date(time1);
			    const date2 = new Date(time2);
			    
			    // 验证日期是否有效
			    if (isNaN(date1.getTime()) || isNaN(date2.getTime())) {
			        throw new Error("无效的时间格式");
			    }
			    
			    // 计算时间差（毫秒），取绝对值确保结果为正数
			    const diffMs = Math.abs(date1 - date2);
			    
			    // 转换为总秒数（毫秒部分会被自动取整）
			    const totalSeconds = Math.floor(diffMs / 1000);
			    
			    // 计算分钟和剩余秒数
			    const minutes = Math.floor(totalSeconds / 60);
			    const seconds = totalSeconds % 60;
			    
			    // 格式化为两位数并拼接
			    return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
			},
			
			//计算两个 ISO 8601 时间字符串（如 "2025-10-17T16:14:53Z"）之间的差值，最终格式化为 "00h00m" 字符串
			TimeDifferenceToHHmm(start, end) {
			    const startDate = new Date(start);
			    const endDate = new Date(end);
			
			    // 检查日期是否有效
			    if (isNaN(startDate) || isNaN(endDate)) {
			        return null; // 或抛出错误
			    }
			
			    const diffMs = Math.abs(endDate - startDate);     // 毫秒差
			    const diffSeconds = Math.floor(diffMs / 1000);    // 转为整数秒（向下取整）
			    const totalMinutes = Math.floor(diffSeconds / 60); // 完整分钟数（丢弃不足1分钟的秒）
			
			    const hours = Math.floor(totalMinutes / 60);
			    const minutes = totalMinutes % 60;
			
			    return `${String(hours).padStart(2, '0')}h${String(minutes).padStart(2, '0')}m`;
			},
			
			
			//除以1000
			convertAndDivide(str,fixedNum) {
				// 将字符串转换为浮点数
				const num = parseFloat(str);
				// 检查转换是否成功
				if (isNaN(num)) {
					throw new Error("无效的数字字符串");
				}
				// 除以1000后保留一位小数（四舍五入）
				const divided = num / 1000;
				// 直接使用toFixed(1)进行四舍五入并保留一位小数
				return divided.toFixed(fixedNum);
			},
			
			//字符串保留两位小数
			formatNumber(str, fixedNum) {
				// 1. 处理 null、undefined 或非字符串/数字输入
				if (str == null || str === '') {
					return '0.' + '0'.repeat(fixedNum); // 例如 fixedNum=2 → "0.00"
				}

				// 2. 转为数字
				const num = parseFloat(str);

				// 3. 检查是否为有效数字
				if (isNaN(num)) {
					return '0.' + '0'.repeat(fixedNum);
				}

				// 4. 手动四舍五入（避免 toFixed 的浮点误差问题）
				const multiplier = Math.pow(10, fixedNum);
				const rounded = Math.round(num * multiplier) / multiplier;

				// 5. 使用 toFixed 确保小数位数（此时 rounded 已是精确值）
				return rounded.toFixed(fixedNum);
			},
			
			// 方法1：使用映射表直接转换
			convertCurrencyCodeToSymbol(code) {
			  const currencyMap = {
			    'USD': '$',    // 美元
			    'EUR': '€',    // 欧元
			    'GBP': '£',    // 英镑
			    'JPY': '¥',    // 日元
			    'CNY': '¥',    // 人民币
			    'AUD': 'A$',   // 澳元
			    'CAD': 'C$'    // 加元
			  };
			  // 不区分大小写处理
			  return currencyMap[code.toUpperCase()] || code;
			},
			
			CoverTypeToACDC(type) {
			    if (type == "Type 1" || type == "Type 2 (cable)" || type == "Type 2 (socket)" || type == "GBT AC") {
			        return "AC"
			    }
			    return "DC"
			},
			
			
			FormatSeconds(seconds) {
			    let numSeconds = parseInt(seconds);
			    let min = Math.floor(numSeconds / 60) >= 10? Math.floor(numSeconds / 60) : '0' + Math.floor(numSeconds / 60);
			    let sec = (numSeconds % 60) >= 10? (numSeconds % 60) : '0' + (numSeconds % 60);
			    return min + ':' + sec;
			},
			
			//将一个表示总秒数的字符串（如 "300"）转换为 "00h00m00s" 格式的字符串
			SecondsStringToHHmmss(secondsStr) {
				const totalSeconds = parseInt(secondsStr, 10);
				
				// 处理无效或负数输入
				if (isNaN(totalSeconds) || totalSeconds < 0) {
					return "00h00m00s"; // 或抛错 / 返回 null
				}

				const hours = Math.floor(totalSeconds / 3600);
				const minutes = Math.floor((totalSeconds % 3600) / 60);
				const seconds = totalSeconds % 60;

				return `${String(hours).padStart(2, '0')}h${String(minutes).padStart(2, '0')}m${String(seconds).padStart(2, '0')}s`;
			},
			
			//将两个表示小数的字符串（如 "12.345" 和 "67.891"）相加，并四舍五入保留两位小数
			AddAndRound(aStr, bStr) {
			  // 强制转换为字符串（处理数字、null、undefined 等）
			  aStr = String(aStr).trim();
			  bStr = String(bStr).trim();

			  // 如果转换后是 "null" 或 "undefined"，需要特殊处理
			  if (aStr === 'null' || aStr === 'undefined' || bStr === 'null' || bStr === 'undefined') {
				throw new Error('Invalid input: null or undefined');
			  }

			  // 辅助函数：获取小数位数
			  function getDecimalPlaces(s) {
				if (!s || s === '-') return 0;
				const parts = s.split('.');
				return parts.length === 2 ? parts[1].length : 0;
			  }

			  // 简单验证是否为数字格式（允许负号）
			  if (!/^-?\d*\.?\d*$/.test(aStr) || !/^-?\d*\.?\d*$/.test(bStr)) {
				throw new Error('Invalid number string');
			  }

			  const aDecimals = getDecimalPlaces(aStr);
			  const bDecimals = getDecimalPlaces(bStr);
			  const maxDecimals = Math.max(aDecimals, bDecimals);

			  const factor = Math.pow(10, maxDecimals);
			  const aInt = Math.round(parseFloat(aStr) * factor);
			  const bInt = Math.round(parseFloat(bStr) * factor);
			  const sum = (aInt + bInt) / factor;

			  return sum.toFixed(2);
			}
		}
	}
</script>

<style>
	
	page {
		background-color: #F2F4F6;
	}
	
	.content {
		
	}
	
	.custom-nav {
		position: fixed;
		left: 0;
		top: 0;
		width: 100%;
		display: flex;
		align-items: center;
		background: #fff;
		box-shadow: 0 1px 3px rgba(0,0,0,0.1);
	}
	
	.back-btn {
	  padding: 0 20rpx;
	}
	
	.container-view {
		margin: 32rpx;
		padding: 16rpx 40rpx 16rpx 24rpx;
		background-color: white;
		border-radius: 24rpx;
	}	
	
	.line-content {
		min-height: 60rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;	
	}
	
	.line-left {
		font-family: PingFang SC; 
		font-size: 28rpx; 
		font-weight: normal; 
		line-height: 28rpx;
		color: #000000;
		display: flex;
		align-items: center;
	}
	
	.line-right {
		font-family: PingFang SC; 
		font-size: 24rpx; 
		font-weight: normal; 
		line-height: 40rpx; 
		text-align: right;
	}

	.icon-image {
		width: 36rpx;
		height: 36rpx;
	}
	
	.info-content {
		padding: 0 32rpx; 
		height: 112rpx;
		font-family: PingFang SC; 
		font-size: 32rpx; 
		font-weight: normal; 
		line-height: 48rpx; 
		display: flex; 
		align-items: center;
	}
	.idle-free-content {
		padding: 28rpx 32rpx;
		border-radius: 12rpx;
		border: 2rpx solid rgba(50, 187, 120, 0.5);
		background-color: #E6FEF0;
		display: flex;
		align-items: center;
	}
	
	.idle-free-text {
		margin-left: 16rpx;
		font-family: PingFang SC; 
		font-size: 28rpx; 
		font-weight: normal; 
		color: rgba(0, 0, 0, 0.9);
	}
	
	.bill-content {
		padding: 0 32rpx;
	}
	
	.bill-detail-content {
		margin: 32rpx 0;
		padding-left: 24rpx;
		padding-right: 40rpx;
		border-radius: 24rpx;
		background-color: white;
	}
	
	.time-content {
		height: 112rpx;
		display: flex;
		align-items: center;
		border-bottom: 2rpx solid #EBEAEF;;
	}
	
	.warning-view-content {
		padding-left: 32rpx;
		height: 100rpx;
		background-color: #FFF0ED;
		font-family: PingFang SC; 
		font-size: 28rpx; 
		font-weight: normal; 
		line-height: 48rpx;
		color: rgba(0, 0,0 0.9);
		display: flex;
		align-items: center;
	}
	
</style>
